package org.liangsy.rest.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.liangsy.common.bean.Result;
import org.liangsy.common.constans.BaseConstans;
import org.liangsy.common.utils.MyBeanUtils;
import org.liangsy.rest.user.dto.UserLoginDto;
import org.liangsy.rest.user.dao.entity.SysUser;
import org.liangsy.rest.user.dao.mapper.SysUserMapper;
import org.liangsy.rest.user.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper; ;

    @Override
    public Result register(UserLoginDto userLoginDto) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userLoginDto.getUserName());
        queryWrapper.eq("status_cd", BaseConstans.COMMON_STATUS.COMMON_STATUS_0001);
        Long count = sysUserMapper.selectCount(queryWrapper);
        if (count > 0){
            return Result.failed("用户名已存在");
        }

        //todo 验证用户长度，验证密码长度安全性，验证邮箱

        SysUser sysUser = new SysUser();
        MyBeanUtils.copyProperties(userLoginDto, sysUser);
        sysUser.setStatusCd(BaseConstans.COMMON_STATUS.COMMON_STATUS_0001);
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        MyBeanUtils.initNullPropertyNames(sysUser);
        boolean save = save(sysUser);
        return Result.success(save);
    }

    @Override
    public Result login(UserLoginDto userLoginDto) {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userLoginDto.getUserName());
        queryWrapper.eq("user_password", userLoginDto.getUserPassword());
        queryWrapper.eq("status_cd", BaseConstans.COMMON_STATUS.COMMON_STATUS_0001);
        queryWrapper.last("limit 1");
        SysUser sysUser  = sysUserMapper.selectOne(queryWrapper);
        if (sysUser==null) {
            return Result.failed("用户名或密码错误");
        }
        userLoginDto.setUserPassword(null);
        userLoginDto.setLoginEmail(sysUser.getLoginEmail());
        return Result.success(userLoginDto);
    }

}